#pragma once
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Comm.h"
#include "Log.h"
using namespace LogMudule;

void Send(int sock, const Protocol &pro)
{

    int ret = ::send(sock, &pro, 4 + 4 + pro.len_, 0);
    if (ret < 0)
    {
        perror("Send send");
    }
}
void SEND(int sock, const Protocol &pro, size_t len)
{
    const char *buffer = reinterpret_cast<const char *>(&pro);
    while (len > 0)
    {
        ssize_t sent = send(sock, buffer, len, 0);
        if (sent <= 0)
        { /* 处理错误 */
        }
        len -= sent;
        buffer += sent;
    }
}
void recv_N(int fd, char *buf, int n)
{
    int total{}, ret;
    while (total < n)
    {
        ret = ::recv(fd, buf + total, n - total, 0);
        total += ret;
    }
}

Protocol Recv(int sockfd)
{
    struct Protocol proto{};

    recv_N(sockfd, (char *)&proto.be_, sizeof(int));
    recv_N(sockfd, (char *)&proto.len_, sizeof(proto.len_));
    recv_N(sockfd, proto.buf, proto.len_);

    return proto;
}

int Connnect()
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("socket");
        Die(SOCKET_ERR);
    }
    sockaddr_in serv_addr{};
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(SERVER_PORT);
    inet_pton(AF_INET, SERVER_IP.c_str(), &serv_addr.sin_addr);

    if (connect(sockfd, (sockaddr *)&serv_addr, sizeof(serv_addr)))
    {
        perror("connect");
        close(sockfd);
        return -1;
    }
    return sockfd;
}